from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer, BadData

from verifcations import smstimes


def generate_access_token(openid):
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,
                                                 expires_in=smstimes.token_time)

    data = {'openid': openid}

    token = serializer.dumps(data)

    return token.decode()


def check_access_token(access_token):
    serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,
                                                 expires_in=smstimes.token_time)

    try:
        data = serializer.loads(access_token)

    except BadData:
        return None
    else:
        return data.get('openid')